# -*- coding:utf-8 -*-
# !/usr/bin/python3


import os, re
import xlwt, xlrd
import openpyxl
import requests, json


def update():
    os.chdir(r"D:\code\sc\auto-test")
    f = os.popen("git pull http://10.0.7.14/qa/auto-test.git hyhive_develop")
    pr = f.read()
    print(pr.encode("utf-8"))


def get_report_result(taskname):
    cmd = "curl -s \"http://test:test@10.0.7.247/job/TEST-DEPLOY-TEST/job/%s/allure/data/suites.json\"" % taskname
    f = os.popen(cmd)
    pr = f.read()
    prdict = json.loads(pr)
    # 处理
    result_list = prdict["children"][0]["children"][0]["children"][0]["children"]
    # print(result_list)
    for case in result_list:
        result_dict[case["name"]] = case["status"]
        if case["status"] != "passed":
            fail_dcit[case["name"]] = case["status"]
    return


num_sum = []


def demo(root_dir):
    os.chdir(root_dir)
    search_items = os.listdir(root_dir)
    for sub in search_items:
        s = os.path.join(root_dir, sub)
        if os.path.isdir(s):
            if re.search("configuration", s, re.I):
                continue
            demo(root_dir=s)
        elif re.search("test_.+\.py$", s) and re.search("\d{4,5}", s):
            # chaxun
            casename = re.search("test_.+\.py$", s).group(0).replace(".py", "")
            id_demo = re.search("\d{4,5}", s).group(0)
            f = os.popen("git blame %s" % s)

            pr = f.buffer.read().decode('utf-8')
            # if id_demo == "8284":
            #     print("git log --follow %s  | find \"Author\"" % s)
            #     print(pr)
            # f = os.popen("git log --follow %s  | find \"Date:\"" % s)
            # prdate = f.read()
            # print(pr)
            #处理pr，取最老一条记录
            compile = re.compile("\(.+\)")
            compliestr = re.findall(compile, pr)[-1]
            ccdate = re.compile("\d{4}-\d{2}-\d{2}")
            datestamp = re.search(ccdate, compliestr).group()
            # createtime = datestamp.replace("Date:   ", "").replace(" +0800", "")
            # import datetime
            # createtime_form = datetime.datetime.strptime(createtime, '%a %b %d %H:%M:%S %Y')
            # createtime_form = createtime_form.strftime("%Y-%m-%d")
            # print(createtime_form)

            cccpile = re.compile("\([^\s]+\s")
            author_string = re.search(cccpile, pr).group()
            author = author_string.replace("(","").replace(" ","")
            if casename in result_dict and result_dict[casename] != "passed":
                result = result_dict[casename]
                writeexcel(author, id_demo, datestamp, result)
                num_sum.append(id_demo)
            elif casename in result_dict:
                writeexcel(author, id_demo, datestamp)
                num_sum.append(id_demo)
            else:
                writeexcel(author, id_demo, datestamp, result="no result")
                num_sum.append(id_demo)


def writeexcel(sheetname, caseid, createtime, result=None):
    # workbook = openpyxl.load_workbook('e:\python lianxi\income.xlsx')

    # swtich sheet & write
    if result:
        inputlist = [createtime, caseid, result]
    else:
        inputlist = [createtime, caseid]
    namelist = workbook.sheetnames
    try:
        sheetind = namelist.index(sheetname)
        workbook._active_sheet_index = sheetind
        ws = workbook.active
        ws.append(inputlist)
    except:
        print(sheetname + "---" + caseid)
        sheetind = namelist.index("other")
        workbook._active_sheet_index = sheetind
        ws = workbook.active
        ws.append(inputlist)
    # sheets = workbook.sheetnames
    # ws = workbook[sheets[n]]


def generate_excel(sheetlist):
    global workbook
    workbook = openpyxl.Workbook()
    for sheet in sheetlist:
        workbook.create_sheet(sheet)


sheetlist = ["hu.xiaoli", "liao.simei", "liutanyuan", "heqiang1992", "other"]

update()
result_dict = {}
fail_dcit = {}

generate_excel(sheetlist)
taskName = ["TEST-CI-Cinder", "TEST-CI-Unicorn", "TEST-CI-Project", "TEST-CI-Glance", "TEST-CI-Resource", "TEST-CI-HA"]
for name in taskName:
    print(name)
    get_report_result(taskname=name)

demo(root_dir=r"D:\code\sc\auto-test\testCase\hyhive_testCase\HyhiveV2")
demo(root_dir=r"D:\code\sc\auto-test\testCase\unicorn_testCase")

print("总共失败: " + str(len(fail_dcit)))
print("总共: " + str(len(num_sum)))
workbook.save(r'D:\code\sc\case.xlsx')
